from django.http import StreamingHttpResponse
from django.http import HttpResponse
import json
from agent.chat_stream_agent import create_agent

def event_stream(question):
    """生成器：逐个发送 token"""
    def on_token(token):
        # 发送每个 token 作为 SSE 消息
        yield f"data: {json.dumps({'token': token})}\n\n"

    # 调用流式 agent
    for token in create_agent(question, on_token):
        yield token

def stream_chat(request):
    if request.method == "GET":
        question = request.GET.get("question", "").strip()
        if not question:
            data = {"code": 400, "msg": "问题不能为空", "data": ""}
            return HttpResponse(json.dumps(data), status=400)

        # 返回流式响应
        response = StreamingHttpResponse(
            event_stream(question),
            content_type="text/event-stream"
        )
        response["Cache-Control"] = "no-cache"
        response["Connection"] = "keep-alive"
        response["X-Accel-Buffering"] = "no"  # 禁用 Nginx 缓冲
        return response

    return HttpResponse(json.dumps({"code": 405, "msg": "Method not allowed"}), status=405)
